package user

import (
	partner "gitee.com/binny_w/gin-partner"
	"gitee.com/binny_w/gin_starter/model/rsa"
	"gitee.com/binny_w/go-util"
	util2 "gitee.com/binny_w/go-util/v2"
	"github.com/gin-gonic/gin"
	"time"
)

func myPassword(c *gin.Context) {
	uRow := infoFromCtxNoFixer(c)
	if uRow == nil {
		return
	}
	var err error
	old := c.PostForm("old")
	if old, err = rsa.Decode(old); err != nil {
		partner.WriteJsonError(c, 690, err.Error())
		return
	} else if len(old) < 6 || len(old) > 20 || !util.StrCheckPass(old, uRow.ToStr("pasd")) {
		partner.WriteJsonError(c, 691, "密码错误")
		return
	}
	pass := c.PostForm("new")
	if pass, err = rsa.Decode(pass); err != nil {
		partner.WriteJsonError(c, 692, err.Error())
		return
	} else if len(pass) < 6 || len(pass) > 20 || pass == old {
		partner.WriteJsonError(c, 693, "新密码6至20位，且不能与当前相同")
		return
	} else if pass, err = util.StrHashPass(pass); err != nil {
		partner.WriteJsonError(c, 694, err.Error())
		return
	}
	if _, err = MdlUser.Table.UpdateById(c, &util2.MysqlRow{
		"pasd":       pass,
		"updated_at": time.Now().Unix(),
	}, uRow.ToInt64("id")); err != nil {
		partner.WriteJsonError(c, 695, err.Error())
		return
	}
	partner.WriteJsonSuccess(c, nil)
}
